import dayjs from 'dayjs'
import { INVOICE_TITLE_TYPE, INVOICE_STATUS } from '../../utils/constants'
import { STORAGE_KEY } from '../../utils/storage'
import { queryRegionApi } from '../../api/index'

// 是否展示tab   以及当前tab的索引
export function showInvoiceTabs(invoice) {
    const { AlreadyInvoiceInfo, UnInvoiceInfo } = invoice
    const showTabs = AlreadyInvoiceInfo.length + UnInvoiceInfo.length > 1
    return {
        showTabs,
        currentTab: UnInvoiceInfo.length > 0? 0: 1
    }
}

/**
 * 
 * @param {*} id formId
 * @param {*} forms 发票表单列表
 * @returns 
 */
export function toggleForm(id, forms) {
    forms.forEach(item => {
        if(item.id === id) {
            item.open = !item.open
        }
    })

    return forms
}

/**
 * 
 * @param {*} items 修改的对象数组
 * @param {*} forms 
 * @returns 
 */
export function editForm(items, forms) {
    
    // 表单输入 onChange事件 给表单赋值
    forms.forEach(p => {
        items.forEach(edit => {
            const {pId, id, eValue} = edit
            if(p.id === pId) {
                p.list.forEach(item => {
                    if(item.id === id) {
                        item.value = eValue
                    }
                })
                        
                if(id === 3) {
                    const pIndex = p.list.findIndex(l => l.id === 5)
                    if(eValue !== 0) {
                        if(pIndex > -1) {
                            p.list.splice(pIndex, 1)
                        }
                    } else if(pIndex === -1) {
                        p.list.push({
                            id: 5,
                            required: true,
                            mode: 'text',
                            title: '纳税人识别号',
                            label: '税号',
                            value: '',
                            placeholder: '请输入纳税人识别号'
                        })

                        p.list.sort((a, b) => a.id - b.id)
                    }
                }
            }
        })
    })

    return forms
}

/**
 * 
 * @param {*} type 1 未申请  2 已申请
 * @param {*} invoice 发票接口详情
 * @param {*} order 订单详情
 * @returns 当前发票列表
 */
export function invoiceForm(unTab, invoice, order, callback) {

    const {SupplierInfo, AlreadyInvoiceInfo, UnInvoiceInfo} = invoice

    const _invoiceTypes = Object.keys(INVOICE_TITLE_TYPE)
    let _invoices = unTab? UnInvoiceInfo: AlreadyInvoiceInfo

    let forms = []

    if(_invoices && _invoices.length > 0) {
        _invoices.forEach((item, index) => {

            let containFy = false
            let isRefundFee = false
            let justFy = false
            if(item.InvoiceDetail) {
                containFy = item.InvoiceDetail.includes('保险') || item.InvoiceDetail.includes('增值服务')
                justFy = item.InvoiceDetail.includes('增值服务') && item.InvoiceDetail.length === 1
                isRefundFee = item.InvoiceDetail.includes('船票退票手续费')
            }
            // 公告栏
            let notice = ''
            let invoiceTypeTitle = '电子发票'
            const title = isRefundFee? '船票退票手续费': '船票'
            const content = '由供应商提供纸质发票快递到收票地址（需到付）'

            // 退票手续费
            const _offlineSetting = isRefundFee? SupplierInfo.RefundFeeOfflineInvoiceType: SupplierInfo.OfflineInvoiceType
            const _invoiceType = isRefundFee? SupplierInfo.RefundFeeInvocingType: SupplierInfo.InvocingType

            let dateOfInvoice = dayjs(order.departureInfo.departureDateTime).add(1, 'day').format('YYYY-MM-DD')
            if(dayjs(order.departureInfo.departureDateTime).isBefore(dayjs())) {
                dateOfInvoice = dayjs().add(1, 'day').format('YYYY-MM-DD')
            }

            if(_invoiceType === 1 && _offlineSetting === 2) {
                if(!containFy) {
                    invoiceTypeTitle = '纸质发票'
                    notice = `${title}${content}`

                    // 纸质发票不显示
                    dateOfInvoice = ''
                } else {
                    invoiceTypeTitle = '电子发票+纸质发票'
                    notice = `${title}${content}，附加产品在此处开具电子发票`
                    

                    if(justFy) {
                        invoiceTypeTitle = '电子发票'
                        notice = ''
                    }
                }
            }

                    
            let mobile = ''
            let emailStr = ''
            
            mobile = wx.getStorageSync(STORAGE_KEY.mobile) || ''
            emailStr = wx.getStorageSync(STORAGE_KEY.email) || ''
            if(order.mobile) {
                mobile = order.mobile
            }
            
            if(order.email) {
                emailStr = order.email
            }
            if(item.TelNo) {
                mobile = item.TelNo
            }


            if(item.Email) {
                emailStr = item.Email
            }

            // 详细地址
            let subtitle = ''
            // && !item.InvoiceDetail.includes('票款')
            if(item.InvoiceDetail && item.InvoiceDetail.length > 0) {
                subtitle = `金额包括: ${item.InvoiceDetail.join('+')}`
            } else if(item.InvoiceAmount <= 0) {
                subtitle = '暂无可开票项'
            }


            let formList = [{
                id: 1,
                mode: 'label',
                label: '发票类型',
                value: invoiceTypeTitle,
            },{
                id: 2,
                mode: 'label',
                label: '发票金额',
                // tag: SupplierInfo.InvocingType === 0 && !isRefundFee && item.InvoiceAmount > 0? '船票即发票': '',
                tag: '',
                subtitle,
                value: `¥${item.InvoiceAmount}`,
            },{
                id: 3,
                mode: 'tab',
                label: '抬头类型',
                value: item.TitleType,
                data: _invoiceTypes
            },{
                id: 4,
                required: true,
                mode: 'search',
                label: '发票抬头',
                value: item.InvoiceTitle || '',
                placeholder: '请输入发票抬头'
            }]
            

            if(item.TitleType === 0) {
                formList.push({
                    id: 5,
                    required: true,
                    mode: 'text',
                    label: '税号',
                    title: '纳税人识别号',
                    value: item.InvoiceTaxNo || '',
                    placeholder: '请输入纳税人识别号'
                })
            }
            if(invoiceTypeTitle !== '纸质发票') {
                formList.push({
                    id: 6,
                    required: true,
                    mode: 'text',
                    label: '收票邮箱',
                    value: emailStr || '',
                    placeholder: '开具发票后自动发送'
                })
            }

            formList.sort((a, b) => a.id - b.id)

            let dateTime = ''
            // 开票失败，不显示开票时间
            const dateTitle = item.InvoiceTime? '开票': '申请'
            // 展示开票时间的条件
            const condition = item.InvoiceStatus !== 2
            const _time = item.InvoiceTime || item.CreateTime
            if(condition && _time) {
                dateTime = condition? `${dateTitle}时间: ${dayjs(_time).format('YYYY年MM月DD日 HH:mm:ss')}`: ''
            }

            const includePaperInvoice = invoiceTypeTitle.includes('纸质发票')
            if(includePaperInvoice) {

                // FIXME: 发票有几个就请求几次 open 会有问题
                getArea(item.AddressShow, function({
                    addressDetail,
                    addressRange,
                    preAddressRange,
                    addressIndexList,
                    preAddressIndexList
                }) {

                    let province = '', city = '', area = ''
                    let addressArea = ''
                    if(addressRange && addressRange.length > 0 && addressIndexList && addressIndexList.length > 0) {

                        if(addressRange[0] && addressRange[0].length > 0 && addressRange[0][addressIndexList[0]]) {
                            province = addressRange[0][addressIndexList[0]].name
                        }

                        if(addressRange[1] && addressRange[1].length > 0 && addressRange[1][addressIndexList[1]]) {
                            city = addressRange[1][addressIndexList[1]].name
                        }

                        if(addressRange[2] && addressRange[2].length > 0 && addressRange[2][addressIndexList[2]]) {
                            area = addressRange[2][addressIndexList[2]].name
                        }
                        
                        
                        addressArea = addressIndexList[0] === -1 ? '请选择' : `${province} ${city} ${area}`
                    }
    
                    formList.push({
                        id: 7,
                        required: true,
                        mode: 'picker',
                        label: '收票地区',
                        value: addressArea
                    },{
                        id: 8,
                        required: true,
                        mode: 'text',
                        label: '详细地址',
                        value: addressDetail || '',
                        placeholder: '请填写详细地址'
                    },{
                        id: 9,
                        required: true,
                        mode: 'text',
                        label: '联系人',
                        value: item.Bank || '',
                        placeholder: '请填写联系人'
                    },{
                        id: 10,
                        required: true,
                        mode: 'text',
                        label: '联系电话',
                        value: mobile || '',
                        placeholder: '请填写联系电话'
                    })

                    forms.push({
                        id: item.CreateTime? dayjs(item.CreateTime).valueOf(): dayjs().valueOf(),
                        invoiceId: item.ApplyId,
                        notice,
                        status: INVOICE_STATUS[item.InvoiceStatus],
                        dateTime,
                        detail: item.InvoiceDetail,
                        canEdit: item.InvoiceStatus < 1,
                        list: formList,
                        open: true,

                        addressDetail,
                        addressRange,
                        preAddressRange,
                        addressIndexList,
                        preAddressIndexList,
                        includePaperInvoice,
                        province,
                        city,
                        area,

                        dateOfInvoice
                    })


                    if(forms.length > 1) {
                        forms.sort((a, b) => b.id - a.id)
                        forms.forEach((item, i) => {
                            item.open = false
                            if(i === 0) {
                                item.open = true
                            }
                        })
                    }
                    callback && callback(forms)
                })
                return
            }

            forms.push({
                id: item.CreateTime? dayjs(item.CreateTime).valueOf(): dayjs().valueOf(),
                invoiceId: item.ApplyId || 0,
                notice,
                status: INVOICE_STATUS[item.InvoiceStatus],
                dateTime,
                
                detail: item.InvoiceDetail,
                canEdit: item.InvoiceStatus < 1,
                list: formList,
                open: true,
                includePaperInvoice,
                dateOfInvoice
            })
        })
    }

    // 与当前时间 最近的在最上面
    if(forms.length > 1) {
        forms.sort((a, b) => b.id - a.id)
        forms.forEach((item, i) => {
            item.open = false
            if(i === 0) {
                item.open = true
            }
        })
    }
    callback && callback(forms)
}

export function getProvinceAndCityAndDistrict (provinceId, cityId) {
    let type = 0
    let relationId = 0
    if (provinceId) {
        type = 1
        relationId = provinceId
    }
    if (provinceId && cityId) {
        type = 2
        relationId =cityId
    }
    const params = {
      Type: type,
      RelationId: relationId
    }

    return queryRegionApi(params).then(res => {
      if (res.status === 200 && res.data) {
        const result = res.data
        if(result.Code == 10000 && result.Data){
          return result.Data
        }
      }
    }).catch(err => {
      console.log('获取地址列表失败')
    })
}

/**
 * 获取省列表
 */
 export function getProvinceList() {
    return getProvinceAndCityAndDistrict()
        .then(res => {
            const provinceList = res
            return provinceList
        })
}

/**
 * 获取城市列表
 * @param {Number} provinceId 
 * @returns {Promise}
 */
 export function getCityList (provinceId) {
return getProvinceAndCityAndDistrict(provinceId)
    .then(res => {
        const cityList = res
        return cityList
    })
}

/**
 * 获取区列表
 * @param {Number} provinceId 
 * @param {Number} cityId 
 * @returns {Promise}
 */
export function getDistrictList (provinceId, cityId) {
    return getProvinceAndCityAndDistrict(provinceId, cityId)
        .then(res => {
            const districtList = res
           
            return districtList
        })
}


let loading = false
// 获取地区
export function getArea(AddressShow, callback) {
    // // FIXME: 现在可能有多个发票
    let addressRange = []
    let preAddressRange = []
    let addressDetail = ''

    let addressObj = null
    let provinceId = 0
    let cityId = 0
    let districtId = 0
    
    let addressIndexList = [-1, -1, -1]
    let preAddressIndexList = [-1, -1, -1]

    if(AddressShow) {
        addressObj = JSON.parse(AddressShow)
        provinceId = addressObj.provinceId
        cityId = addressObj.cityId
        districtId = addressObj.districtId
    }
    if(loading) {
        // wx.setStorageSync('area_loading', 1);
        return
    }
    getProvinceList()
    .then(provinceList => {
        if (provinceList) {
            addressRange = [provinceList]
            provinceId = provinceId || provinceList[0].id
            getCityList(provinceId)
            .then(cityList => {
                if (cityList) {
                    addressRange[1] = cityList
                    cityId = cityId || cityList[0].id
                    getDistrictList(provinceId, cityId)
                    .then(districtList => {

                        addressRange[2] = districtList

                        districtId = districtId || districtList[0].id

                        preAddressRange = JSON.parse(JSON.stringify(addressRange))

                        const provinceIndex = provinceList.findIndex(item => item.id === provinceId)
                        const cityIndex = cityList.findIndex(item => item.id === cityId)
                        const districtIndex = districtList.findIndex(item => item.id === districtId)
                        if (addressObj) { // 表示回填
                            addressDetail = addressObj.addressDetail
                            addressIndexList = [provinceIndex, cityIndex, districtIndex]
                            preAddressIndexList = [provinceIndex, cityIndex, districtIndex]
                        }
                        loading = false
                        callback && callback({
                            addressDetail,
                            addressRange,
                            preAddressRange,
                            addressIndexList,
                            preAddressIndexList
                        })
                        

                    })
                }
            })
        }
    })
}